#!/usr/bin/env python3
"""
调试服务器启动问题
"""

import sys
import traceback

def test_imports():
    """测试所有导入"""
    print("测试导入...")
    
    try:
        import fastapi
        print(f"✅ FastAPI: {fastapi.__version__}")
    except Exception as e:
        print(f"❌ FastAPI导入失败: {e}")
        return False
    
    try:
        import uvicorn
        print(f"✅ Uvicorn: {uvicorn.__version__}")
    except Exception as e:
        print(f"❌ Uvicorn导入失败: {e}")
        return False
    
    try:
        import sqlalchemy
        print(f"✅ SQLAlchemy: {sqlalchemy.__version__}")
    except Exception as e:
        print(f"❌ SQLAlchemy导入失败: {e}")
        return False
    
    try:
        from backend import main
        print("✅ backend.main导入成功")
    except Exception as e:
        print(f"❌ backend.main导入失败: {e}")
        traceback.print_exc()
        return False
    
    try:
        from backend.main import app
        print("✅ app对象导入成功")
        print(f"App类型: {type(app)}")
    except Exception as e:
        print(f"❌ app对象导入失败: {e}")
        traceback.print_exc()
        return False
    
    return True

def test_database():
    """测试数据库连接"""
    try:
        print("测试数据库连接...")
        from backend.database import engine, SessionLocal
        
        # 测试连接
        with SessionLocal() as db:
            print("✅ 数据库连接成功")
            return True
    except Exception as e:
        print(f"❌ 数据库连接失败: {e}")
        traceback.print_exc()
        return False

def start_simple_server():
    """启动简单服务器"""
    try:
        print("启动简单服务器...")
        from backend.main import app
        import uvicorn
        
        print("开始运行uvicorn...")
        uvicorn.run(
            app, 
            host="127.0.0.1", 
            port=8000, 
            log_level="debug",
            access_log=True
        )
        
    except Exception as e:
        print(f"❌ 服务器启动失败: {e}")
        traceback.print_exc()

def main():
    print("🔍 调试服务器启动问题")
    print("="*50)
    
    # 测试导入
    if not test_imports():
        print("导入测试失败，退出")
        sys.exit(1)
    
    # 测试数据库
    if not test_database():
        print("数据库测试失败，但继续尝试启动服务器")
    
    # 启动服务器
    print("\n🚀 尝试启动服务器...")
    start_simple_server()

if __name__ == "__main__":
    main()
